package org.exmaple.springframework.beans.factory.support;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;
import org.exmaple.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.util.Objects;

/**
 * @author DeYou
 * @date 2022/10/27
 */
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) {

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass( beanDefinition.getBeanClass() );

        enhancer.setCallback( new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        } );
        //如果ctor 是无参的，调用无参构造方法实例化
        if(Objects.isNull( ctor )) return enhancer.create();
        //如果构造方法是有参的，调用有参方法实例化，
        return enhancer.create(ctor.getParameterTypes(),args);
    }
}